package org.ggn.scoreanalyze.view;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * Created by guin_guo on 2015/12/14.
 */
public class PieFrame extends JFrame {

    public PieFrame(String name, Number yx,Number lh,Number zd,Number jg,Number bjg) {
        PieChart pieChart = new PieChart(yx,lh,zd,jg,bjg);
        add(pieChart.getChartPanel());
        setTitle(name + " 饼图");
        setSize(800, 500);
        setLocation(200, 80);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    class PieChart{
        ChartPanel frame1;
        public PieChart(Number yx,Number lh,Number zd,Number jg,Number bjg){
            DefaultPieDataset data= getDataSet(yx,lh,zd,jg,bjg);
            JFreeChart chart = ChartFactory.createPieChart3D("数据饼图", data, true, false, false);
            //设置百分比
            PiePlot pieplot = (PiePlot) chart.getPlot();
            DecimalFormat df = new DecimalFormat("0.00%");//获得一个DecimalFormat对象，主要是设置小数问题
            NumberFormat nf = NumberFormat.getNumberInstance();//获得一个NumberFormat对象
            StandardPieSectionLabelGenerator sp1 = new StandardPieSectionLabelGenerator("{0}  {2}", nf, df);//获得StandardPieSectionLabelGenerator对象
            pieplot.setLabelGenerator(sp1);//设置饼图显示百分比

            //没有数据的时候显示的内容
            pieplot.setNoDataMessage("无数据显示");
            pieplot.setCircular(false);
            pieplot.setLabelGap(0.02D);

            pieplot.setIgnoreNullValues(true);//设置不显示空值
            pieplot.setIgnoreZeroValues(true);//设置不显示负值
            frame1=new ChartPanel(chart,true);
            chart.getTitle().setFont(new Font("宋体", Font.BOLD,20));//设置标题字体
            PiePlot piePlot= (PiePlot) chart.getPlot();//获取图表区域对象
            piePlot.setLabelFont(new Font("宋体", Font.BOLD,10));//解决乱码
            chart.getLegend().setItemFont(new Font("黑体", Font.BOLD,10));
        }
        public ChartPanel getChartPanel(){
            return frame1;
        }
    }

    private static DefaultPieDataset getDataSet(Number yx,Number lh,Number zd,Number jg,Number bjg){
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("优秀",yx);
        dataset.setValue("良好",lh);
        dataset.setValue("中等",zd);
        dataset.setValue("及格",jg);
        dataset.setValue("不及格",bjg);
        return dataset;
    }

}
